package com.phone.servlet;

import com.phone.DBHelper;
import com.phone.handle.UserHandle;
import com.phone.utils.MessageUtil;
import org.hibernate.Session;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * Created by tisen on 2017/8/22.
 */
@WebServlet(name = "WXXML", urlPatterns = "/xml")
public class WXXMLServlet extends BaseServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String tip = null;
        Session session = DBHelper.getSession();
        try {
            Map<String, String> xml = MessageUtil.parseXml(request);
            String toUserName = xml.get("ToUserName");
            String fromUserName = xml.get("FromUserName");
            String event = xml.get("Event");
            session.beginTransaction();
            UserHandle handle = new UserHandle(session);
            if (event.equals("subscribe") && handle.getByWx(fromUserName) == null) {
                handle.registerByWx(fromUserName, null, null);
            } else {
                tip = "";
            }
        } catch (Exception e) {
            e.printStackTrace();
            tip = "false";
        } finally {
            if (tip == null) {
                tip = "true";
            }
            if (session != null && session.isOpen())
                session.close();
            out(response, tip);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}

